package com.cx.bank.servlet.admin;

import com.cx.bank.handler.MyInVocationHandler;
import com.cx.bank.manager.IManager;
import com.cx.bank.manager.ManagerImpl;
import com.cx.bank.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

/**
 * 更新user
 * @author jxau_scf
 * @date 2021/8/5 - 14:47
 */
@WebServlet(urlPatterns = "/user/doUpdateUser")
public class DoUpdateUserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userId = req.getParameter("userId");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String userFlag = req.getParameter("userFlag");
        String userType = req.getParameter("userType");
        String balance = req.getParameter("balance");

        //给user对象注入信息
        User user = new User();
        user.setUserId(Integer.valueOf(userId));
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setUserFlag(Integer.valueOf(userFlag));
        user.setUserType(userType);
        user.setBalance(Double.valueOf(balance));

        //获取代理对象，方便使用日志
        IManager manager = new ManagerImpl();
        MyInVocationHandler handler = new MyInVocationHandler();
        handler.setUserName(userName);
        handler.setTarget(manager);
        IManager proxy = (IManager)handler.getProxy();

        boolean updateUserStatus = proxy.updateUser(user);

        if (updateUserStatus){
            //更新用户信息成功后
            List<User> userList = null;
            try {
                userList = proxy.findAllUser();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            System.out.println(userList.toString());
            req.setAttribute("userlist", userList);
            //服务端跳转（转发）
            req.getRequestDispatcher("/WEB-INF/jsp/user/admin/allUser.jsp").forward(req, resp);
        }else {
            //更新失败
            req.getRequestDispatcher("/WEB-INF/jsp/error.jsp").forward(req, resp);
        }
    }
}
